package com.digua.base.socket.dispatcher

import com.digua.base.socket.response.ErrorResponse
import com.digua.base.socket.response.Response
import java.util.ArrayDeque
import java.util.Queue


class ResponseProcessEngine {

    private var mThread: EngineThread = EngineThread()

    constructor() {
        mThread.start()
    }

    fun onMessageReceive(message: Response<*>?, dispatcher: IResponseDispatcher?, delivery: ResponseDelivery?) {
        if (message == null || dispatcher == null || delivery == null) return
        val entity = EngineEntity.obtain()
        entity.dispatcher = dispatcher
        entity.delivery = delivery
        entity.isError = false
        entity.response = message
        entity.errorResponse = null
        mThread.add(entity)
    }

    fun onSendDataError(errorResponse: ErrorResponse?, dispatcher: IResponseDispatcher?, delivery: ResponseDelivery?) {
        if (errorResponse == null || dispatcher == null || delivery == null) return
        val entity = EngineEntity.obtain()
        entity.dispatcher = dispatcher
        entity.delivery = delivery
        entity.isError = true
        entity.errorResponse = errorResponse
        entity.response = null
        mThread.add(entity)
    }

    class EngineEntity {
        var isError = false
        var response: Response<*>? = null
        var errorResponse: ErrorResponse? = null
        var dispatcher: IResponseDispatcher? = null
        var delivery: ResponseDelivery? = null

        companion object {
            private val ENTITY_POOL: Queue<EngineEntity> = ArrayDeque(10)
            fun obtain() = ENTITY_POOL.poll() ?: EngineEntity()

            fun release(entity: EngineEntity) = ENTITY_POOL.offer(entity)
        }
    }
}